var selNode = "";
var userId = 0;
var canSearchAll = "true";
layui.config({
    base: baseUrl + '/js/layui/module/'
}).extend({//设定模块别名
    treeSelect: 'treeSelect/treeSelect',//static/js/layui/module/treeSelect/treeSelect.js
    formSelects: 'formSelects/formSelects-v4',//static/js/layui/module/formSelects/formSelects-v4.js
    dtree : 'dtree/dtree'
});
layui.use(['form','layer','laydate','table','laytpl','element','treeSelect','formSelects','dtree'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
    var treeSelect = layui.treeSelect;
    var formSelects = layui.formSelects;
    var dtree = layui.dtree;

    var url = baseUrl + "/industryType/queryByTree";
    var toolbarFun = true;//默认是开启的
    if(refPackageId!=undefined && refPackageId!=null && refPackageId!="" && refPackageId!="0"){ //如果是关联 packageId ，则标识页面来源是 项目私有的
        url = baseUrl + "/industryType/queryByTree?packageId="+refPackageId
        toolbarFun = false;
    }
    var DTree = dtree.render({
        elem: "#commonTree3",
        url: url,
        icon: "2",
        skin:"layui",
        menubar:true,
        // request : {businessTypeBaseId : "businessTypeBaseId"},//指定请求带上的参数 ？？？ 如何动态加上节点参数值？
        /*menubarTips:{
            toolbar:["remove",{menubarId:"zdy",icon:"dtree-icon-rate",title:"自定义menu",handler: function(node,$div){layer.msg(JSON.stringify(node));}}]
        },
        menubarFun:{
            remove: function(checkbarNodes){
                layer.msg(JSON.stringify(checkbarNodes));
                return true;
            }
        },*/
        toolbar:toolbarFun,
        toolbarScroll:"#toolbarDiv",
        toolbarShow:["add","edit","delete"],
        toolbarBtn:[
            [
                //{"label":"级别","name":"level","type":"text"},
                //{"label":"下拉","name":"test","type":"select","optionsData":{"1":"男","2":"女","3":"未知","4":"泰国归来"}}
                {"label":"所属业务类型","name":"businessTypeBaseId","type":"select","optionsData":businessTypes,"disabled":"disabled"}
            ],[
                {"label":"所属业务类型","name":"businessTypeBaseId","type":"select","optionsData":businessTypes}
            ]//第一个[]是新增页的、第二个是自定义编辑页的内容
        ],
        toolbarStyle:{ title:"类型"},
        // toolbarExt:[{toolbarId: "test",icon:"dtree-icon-wefill",title:"自定义toolbar",handler: function(node,$div){layer.msg(JSON.stringify(node));}}],
        toolbarFun: {
            addTreeNode: function(treeNode){
                var submitData = {};
                submitData["id"] = treeNode.nodeId;
                submitData["name"] = treeNode.context;
                submitData["parentId"] = treeNode.parentId;
                submitData["businessTypeBaseId"] = treeNode.businessTypeBaseId;
                $.ajax({
                    type: "POST",
                    url:  baseUrl+'/industryType/save',
                    dataType: 'json',
                    data: submitData,
                    success: function (data) {
                        console.log(data);
                        if(data.code<=0){
                            layer.msg(data.msg);
                            DTree.changeTreeNodeAdd(false);
                        }else{
                            layer.msg("保存成功");
                            DTree.changeTreeNodeAdd(true);
                            DTree.menubarMethod().refreshTree();
                            selNode = "";
                        }
                    },
                    error: function () {
                        layer.msg("保存失败");
                        DTree.changeTreeNodeAdd(false);
                        return ;
                    }
                });
            },
            editTreeLoad: function(treeNode){
                // 这里可以发送ajax请求，来获取参数值，最后将参数值以form能识别的键值对json的形式返回
                // var param = $.ajax({async:false, ...}) //示例发送ajax请求获取参数
                // 这里的param格式为：  {level:treeNode.level, test:"3"};
                // treeNode.businessTypeBaseId 不起作用，无法从treeNode中获取到，所以改成了basicData中获取
                console.log(treeNode.basicData);
                var basicData = JSON.parse(treeNode.basicData);//用户自定义的记录节点数据
                var param = {nodeId:treeNode.nodeId, context:treeNode.context,parentId:treeNode.parentId,businessTypeBaseId:basicData.businessTypeBaseId};
                DTree.changeTreeNodeDone(param); // 配套使用
            },
           addTreeLoad:function (treeNode) {
                // layer.msg(JSON.stringify(treeNode.businessTypeBaseId));
                // 这里可以发送ajax请求，来获取参数值，最后将参数值以form能识别的键值对json的形式返回
                // var param = $.ajax({async:false, ...}) //示例发送ajax请求获取参数
                // 这里的param格式为：  {level:treeNode.level, test:"3"};
               var basicData = JSON.parse(treeNode.basicData);//用户自定义的记录节点数据
                if(treeNode.parentId!=null && treeNode.parentId!=undefined && treeNode.parentId!="0" && treeNode.parentId!=""){
                    var parentParam = DTree.getParentParam(treeNode.nodeId);
                    console.log(parentParam);
                    if(parentParam!=undefined && parentParam!=null){
                        if(JSON.parse(parentParam.basicData).businessTypeBaseId!="0"){
                            basicData = JSON.parse(parentParam.basicData);
                        }
                    }
                }
                var param = {nodeId:treeNode.nodeId, context:treeNode.context,parentId:treeNode.parentId,businessTypeBaseId:basicData.businessTypeBaseId};
                DTree.changeTreeNodeAddDone(param); // 配套使用
            },
            /*loadToolbarBefore: function(buttons, treeNode, $div){
                console.log(buttons);
                layer.msg(JSON.stringify(treeNode));
                // console.log($div);
               /!* if(param.isLeaf){ // 如果是叶子节点
                    buttons.addToolbar = "";  // 取消新增功能
                }*!/

                return buttons; // 将按钮对象返回
            },*/
            editTreeNode: function(treeNode){
                var submitData = {};
                submitData["id"] = treeNode.nodeId;
                submitData["name"] = treeNode.context;
                submitData["parentId"] = treeNode.parentId;
                submitData["businessTypeBaseId"] = treeNode.businessTypeBaseId;
                $.ajax({
                    type: "POST",
                    url:  baseUrl+'/industryType/save',
                    dataType: 'json',
                    data: submitData,
                    success: function (data) {
                        console.log(data);
                        if(data.code<=0){
                            layer.msg(data.msg);
                            DTree.changeTreeNodeEdit(false);
                        }else{
                            layer.msg("保存成功");
                            DTree.changeTreeNodeEdit(true);
                            DTree.menubarMethod().refreshTree();
                            selNode = "";
                        }
                    },
                    error: function () {
                        layer.msg("保存失败");
                        DTree.changeTreeNodeAdd(false);
                        return ;
                    }
                });
            },
            delTreeNode:function (treeNode) {
                var submitData = {};
                submitData["id"] = treeNode.nodeId;
                $.ajax({
                    type: "POST",
                    url:  baseUrl+'/industryType/del',
                    dataType: 'json',
                    data: submitData,
                    success: function (data) {
                        console.log(data);
                        if(data.code<=0){
                            layer.msg(data.msg);
                            DTree.changeTreeNodeDel(false);
                        }else{
                            layer.msg("操作成功");
                            DTree.changeTreeNodeDel(true);
                            DTree.menubarMethod().refreshTree();
                            selNode = "";
                        }
                    },
                    error: function () {
                        layer.msg("操作失败");
                        DTree.changeTreeNodeDel(false);
                        return ;
                    }
                });
            }
        },
        checkbar: true,
        checkbarType: "self",
        /*  checkbarFun: {
              chooseBefore: function($i, node){
                  console.log($i);
                  return true;
              },
              chooseDone: function(nodes){
                  layer.msg(JSON.stringify(nodes));
              }
          },*/
        useIframe:true,
        iframe: {
            iframeElem: "#iframe_content",
            iframeUrl: baseUrl + "/knowledgeBase/queryKnowledgeBase?affectType=c&refPackageId="+refPackageId+"&createUserId="+userId+"&canSearchAll="+canSearchAll,
            //自定义参数传递
            iframeDefaultRequest: {nodeId: "packageId"},// 这里就将nodeId这个参数名称改为了id这个名称
            iframeLoad: "node" // 表示点击任意节点加载iframe
            // , iframeRequest: {username: "zhangsan"} // 这里就自定义了需要传递的参数
        },
        iframeFun:{
            doLoadIframe: function(){ //是否进行加载iframe === > 如果不加载时，默认跳转为空白页 ，用于用户自定义事件
                var param = dtree.getNowParam(DTree);
                if(param.nodeId==0){
                    return false;
                }else{
                    return true;
                }
            }
        }

    });
    // 绑定节点的单击事件
    dtree.on("iframeDone('commonTree3')", function(obj){
       /* layer.msg(JSON.stringify(obj));*/
        console.log(obj);
        if(obj!=undefined){
            selNode = obj.iframeParam.packageId;
        }
    });

});


/*
window.addEventListener('message', function(e)
{
    console.log('listen.....');
    var data = JSON.parse(e.data);
    if(data.key =="postUserMsg" && data.type == "SET"){
        console.log("Receive user info:"+data.value);//userId, roleId, userName,userNo,canSearchAll
        var postUserData = JSON.parse(data.value);
        if(postUserData){
            userId = postUserData.userId;
            canSearchAll = postUserData.canSearchAll;
        }
    }
}, false);*/
